<script setup lang="ts">
import { move } from "@/utils/array";
import { NGrid, gridProps } from "naive-ui";
import Sortable from "sortablejs";
import { onUnmounted, ref, watch } from "vue";

defineProps({} as typeof gridProps);
const emits = defineEmits<{
  (e: "move", oldIndex: number, newIndex: number): void;
}>();

const grid = ref<InstanceType<typeof NGrid>>();
let sortable: Sortable | undefined;

watch(grid, () => {
  sortable?.destroy();
  sortable = undefined;
  if (grid.value?.contentEl !== undefined) {
    sortable = Sortable.create(grid.value!.contentEl!, {
      handle: ".sortable-handle",
      onEnd: ({ oldIndex, newIndex }) => {
        sortable!.sort(move(sortable!.toArray(), newIndex!, oldIndex!));
        emits("move", oldIndex!, newIndex!);
      },
    });
  }
});
onUnmounted(() => sortable?.destroy());
</script>

<template>
  <NGrid ref="grid">
    <slot></slot>
  </NGrid>
</template>
